package com.kirayous.gulimall.cart.config;

import com.kirayous.common.constant.AuthServerConstant;
import com.kirayous.common.vo.MemberRespVo;
import com.kirayous.gulimall.cart.constant.CartConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;
import com.kirayous.gulimall.cart.vo.UserInfoTo;

/**
 * @author KiraYous
 * @version V1.0
 * @Package com.kirayous.gulimall.cart.config
 * @date 2022/3/20 16:59
 */

/**
 * 在执行目标方法之前，判断用户的登录状态。并封装传递(用户信息)给controller
 */
@Resource
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    //这里无法通过@Value进行注入，那我应该如何注入?
//    @Value("${my.domin}")
    private static final String domin="1.14.151.242";
    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(member != null){
            //用户登录
            userInfoTo.setUserId(member.getId());
            userInfoTo.setTempUser(false);
        }

        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //如果没有临时用户一定分配一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后；分配临时用户，让浏览器保存
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();

        //如果没有临时用户一定保存一个临时用户
        if(!userInfoTo.isTempUser()){
            //持续的延长临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            System.out.println("domin:"+domin);
            cookie.setDomain(domin);
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

        //TODO 思考一下这里的threadlocal不释放掉userInfoTo的话，会不会造成数据泄露？

        //由于Threadlocal 的set方法实际上是再当前Thread对象的map里面存值，一旦线程被销毁，那么里面的对象应该也会被回收
        //并且这里的map的对象存的value只能存一个，所以每次进来他都会替换掉上一个的userInfoTo对象，
        //所以其实不用担心内存泄露
        //但是由于处于安全考虑，还是手动remove比较好
        threadLocal.remove();
    }
}
